<?php

/*
 * Form generator class, coz' I'm fed up with
 * coding forms over and over again:)
 * 
 * Example:
 * 
 * $Form = new Form('/new_order.php','post');
 * $Form->addField('text', 'Name:', array('name',''));
 * $Form->addField('text', 'Address:', array('address','Nincs...'));
 * $Form->addField('text', 'Phone/Fax:', array('phone',''));
 * $Form->addField('select', 'Amount', array('year',array(0,1,2,3,4,5,6,7,8,9,10),7));
 * $Form->addField('checkbox', 'Returning customer', array('ret_cust','1',true));
 * $Form->addField('checkbox', '1-day express delivery', array('fast','1',false));
 * 
 * $html = $Form->generate("table");
 * 
 * Chris|cC
 */
class SimpleCcForm {
	
	private $target;
	private $method;
	private $fields;
	private $submitLabel;
	private $separator;
	private $errCode; //hibakód
	
	public function SimpleCcForm($target = "", $method = "post", $submitLabel = "Save")
	{
		$this->errCode = 0;
		$this->target = $target;
		$this->method = $method;
		$this->fields = array();
		$this->submitLabel = $submitLabel != '' ? $submitLabel : "Save";
		$this->separator = '<div style="width:100%; border-bottom:1px dotted gray; margin:10px 0px;"></div>';
		$this->spacer = '<div style="width:100%; margin:10px 0px;"></div>';
	}
	
	/*
	 * Available types:
	 *  - text params[ name, value ]
	 *  - password params[ name ]
	 *  - hidden params[ name, value ]
	 *  - checkbox params[ name, value, checked ]
	 *  - select params[ name, value, selected ]
	 *  - file params[ name ]
	 */
	public function addField($type, $label, $params, $hint="")
	{
		//Init
		$this->errCode = 0;
		$types = array("text","password","hidden","checkbox","select","file");
		$params_req = array("text" => array('name','value'),
							"password" => array('name'),
							"hidden" => array('name','value'),
							"checkbox" => array('name','value','checked'),
							"select" => array('name','value','options','selected'),
							"file" => array('name'));
		//Input validation
		if(!in_array($type,$types)){ $this->errCode = 1; return false; }
		if($label == '') $label = "Field_".count($this->fields);
		//Assign default to missing values
		foreach($params_req[$type] as $param){
			if(!isset($params[$param]) || $params[$param] == ''){ 
				switch($param){
					case "name":
						$params[$param] = isset($params[0]) && $params[0] != '' ? $params[0] : 'field_'.count($this->fields);
						break;
					case "value":
						$params[$param] = isset($params[1]) && $params[1] != '' ? $params[1] : ($type == 'checkbox' ? '1' : '');
						break;
					case "checked":
						$params[$param] = isset($params[2]) && is_bool($params[2]) ? $params[2] : false;
						break;
					case "selected":
						$params[$param] = isset($params[2]) && $params[2] != '' ? $params[2] : '0';
						break;
					case "options":
						$params[$param] = isset($params[1]) && is_array($params[1]) && count($params[1]) > 0 ? $params[1] : array();
						break;
					default:
						break;
				}
			}
		}
		
		//Action
		$this->fields[] = array("type" => $type,
								"label" => $label,
								"params" => $params,
								"hint" => $hint);
	}
	
	public function generate($mode = "blueprint")
	{
		$mode_tags = array("table" => array("container_start" => "<table>",
											"container_end" => "</table>",
											"row_start" => "<tr>",
											"row_end" => "</tr>",
											"field_start" => "<td>",
											"fullrow_field_start" => "<td colspan=\"2\">",
											"field_end" => "</td>",),
						   "blueprint" => array("container_start" => '<div class="container">',
											"container_end" => "</div>",
											"row_start" => '<div class="span-24 last">',
											"row_end" => "</div>",
											"field_start" => '<div class="span-10">',
											"fullrow_field_start" => '<div class="span-23 last">',
											"field_end" => "</div>",));
		$eol = "\n";
		$idt = "	";	//Indent
		if(!isset($mode_tags[$mode])) $mode = "table";
		
		
		$html = $mode_tags[$mode]['container_start'].$eol.$idt.'<form action="'.$this->target.'" method="'.$this->method.'">'.$eol;
		
		foreach($this->fields as $field){
			//Create the param string
			$paramstr = "";
			$exclude = array("checked","selected");
			foreach($field['params'] as $k=>$v){ if(!in_array($k,$exclude)) $paramstr .= $k.'="'.$v.'" '; }
			//Code for the row
			$html .= $idt.$idt.$mode_tags[$mode]['row_start'].$eol;
			//Generate HTML code for the field
			
			$html .= $idt.$idt.$idt.str_replace('>', ' style="text-align:right;">', $mode_tags[$mode]['field_start']).$eol.
					$idt.$idt.$idt.$idt.$field['label'].$eol.
					$idt.$idt.$idt.$mode_tags[$mode]['field_end'].$eol.
					$idt.$idt.$idt.$mode_tags[$mode]['field_start'].$eol;
			switch($field['type']){
				case "text":
				case "password":
				case "hidden":
					//Append to the HTML output
					$html .= $idt.$idt.$idt.$idt.'<input type="'.$field['type'].'" '.$paramstr.' />'.$eol;
					break;
				case "checkbox":
					//Append to the HTML output
					$html .= $idt.$idt.$idt.$idt.'<input type="checkbox" '.$paramstr.' '.($field['params']['checked'] ? 'checked="checked"' : '').' />'.$eol;
					break;
				case "select":
					//Append to the HTML output
					$html .= $idt.$idt.$idt.$idt.'<select '.$paramstr.' >'.$eol;
					$html .= $idt.$idt.$idt.$idt.$idt.'	<option value="" '.($field['params']['selected'] == 0 ? 'selected="selected"' : '').'> - Select one - </option>'.$eol;
					foreach($field['params']['options'] as $value => $label){
						$html .= $idt.$idt.$idt.$idt.$idt.'	<option value="'.$value.'" '.($field['params']['selected'] == $value ? 'selected="selected"' : '').'>'.$label.'</option>'.$eol;
					}
					$html .= $idt.$idt.$idt.$idt.'</select>'.$eol;
					break;
				default:
					break;
			}
			if(isset($field['hint']) && $field['hint'] != '') $html .= $idt.$idt.$idt.$idt.'<abbr title="'.$field['hint'].'">?</abbr>'.$eol;
			$html .= $idt.$idt.$idt.$mode_tags[$mode]['field_end'].$eol;
			$html .= $idt.$idt.$mode_tags[$mode]['row_end'].$eol;
		}
		
		$html .= $idt.$idt.$mode_tags[$mode]['row_start'].$eol;
		$html .= $idt.$idt.$idt.$mode_tags[$mode]['fullrow_field_start'].$eol;
		$html .= $idt.$idt.$idt.$idt.$this->spacer.$eol;
		$html .= $idt.$idt.$idt.$mode_tags[$mode]['field_end'].$eol;
		$html .= $idt.$idt.$mode_tags[$mode]['row_end'].$eol;
		
		$html .= $idt.$idt.$mode_tags[$mode]['row_start'].$eol;
		$html .= $idt.$idt.$idt.$mode_tags[$mode]['field_start'].$eol;
		$html .= $idt.$idt.$idt.$mode_tags[$mode]['field_end'].$eol;
		$html .= $idt.$idt.$idt.$mode_tags[$mode]['field_start'].$eol;
		$html .= $idt.$idt.$idt.$idt.'<input type="submit" value="'.$this->submitLabel.'" />'.$eol;
		$html .= $idt.$idt.$idt.$mode_tags[$mode]['field_end'].$eol;
		$html .= $idt.$idt.$mode_tags[$mode]['row_end'].$eol;
		$html .= $idt.'</form>'.$eol.$mode_tags[$mode]['container_end'].$eol;
		
		return $html;
	}
	
	public function hasError()
    {
        return $this->errCode > 0 ? true : false;
    }

    public function getError()
    {
        return $this->errCode;
    }

    public function setVar($name,$value)
	{
		if(isset($this->{$name})) $this->{$name} = $value;
	}

	public function getVar($name)
	{
		return $this->{$name};
	}
	
}

